package com.bao.ad.advice;

import com.bao.ad.annotation.IgnoreResponseAdvice;
import com.bao.ad.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Nullable;

/**
 * ClassName CommonRseponseDataAdvice
 *
 * @author Bai
 * @version 1.0
 * @date 2019/2/17 0017 下午 20:40
 **/
@RestControllerAdvice
public class CommonRseponseDataAdvice implements ResponseBodyAdvice<Object> {

    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }

        if(returnType.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)){
            return false;
        }

        return true;
    }

    @Nullable
    @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        CommonResponse<Object> commonResponse = new CommonResponse<>(0, "");

        if(null == body){
            return commonResponse;
        } else if (body instanceof CommonResponse){
            commonResponse = (CommonResponse<Object>)body;
        } else {
            commonResponse.setDate(body);
        }
        return commonResponse;
    }
}
